<template>
  <el-card>
    <v-stage
      ref="stage"
      :config="configKonva"
      @mousedown="handleDragstart"
      @mouseup="handleDragend"
      @mousemove="handleMove"
    >
      <v-layer>
        <v-line v-for="(item,index) in lines" :key="index" :config="item" />
      </v-layer>
    </v-stage>
  </el-card>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex'
const width = window.innerWidth
const height = window.innerHeight
export default {
  data() {
    return {
      configKonva: {
        width: width,
        height: height
      },
      painting: false,
      stroke: 'red',
      strokeWidth: 5
    }
  },
  methods: {
    ...mapMutations(['drawNewLine', 'updateNewLine']),
    ...mapActions(['sendDrawNewLine', 'sendUpdateNewLine']),
    handleDragstart(e) {
      if (this.holder && this.nickname === this.holder) {
        this.painting = true
        const newLine = {
          stroke: this.stroke,
          strokeWidth: this.strokeWidth,
          points: [e.evt.layerX, e.evt.layerY]
        }
        this.drawNewLine(newLine)
        this.sendDrawNewLine(newLine)
      }
    },
    handleDragend() {
      if (this.painting) {
        console.log('鼠标松开了')
        this.painting = false
      }
    },
    handleMove(e) {
      if (this.painting) {
        const x = e.evt.layerX
        const y = e.evt.layerY
        const line = this.lines[this.lines.length - 1]
        line.points = line.points.concat([x, y])
        this.updateNewLine(line)
        this.sendUpdateNewLine(line)
      }
    }
  },
  // eslint-disable-next-line vue/order-in-components
  computed: {
    ...mapState(['lines', 'holder', 'nickname'])
  }
}
</script>
